from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from app01 import models
from django.db.models.functions import TruncMonth
from app01.myforms import MyregFrom
from PIL  import Image,ImageDraw,ImageFont
from io import BytesIO,StringIO
from django.contrib.auth.decorators import login_required
import random
import json
from django.contrib import auth
from django.db.models import Count
# Create your views here.
def register(request):
    back_dic={"code":1000,"msg":''}
    form_obj=MyregFrom()
    if request.method=="POST":
        form_obj=MyregFrom(request.POST)
        if form_obj.is_valid():
            clean_data=form_obj.cleaned_data
            clean_data.pop('confirm_password')
            file_obj=request.FILES.get('avatar')
            if file_obj:
                clean_data['avatar'] = file_obj
            models.UserInfo.objects.create_user(**clean_data)
            back_dic['url']='/login/'
        else:
            back_dic['code']=2000
            back_dic['msg']=form_obj.errors
        return JsonResponse(back_dic)
    return render(request,'register.html',locals())
def login(request):
    if request.method=='POST':
        back_dic={'code':1000 ,'msg':''}
        username=request.POST.get('username')
        password=request.POST.get('password')
        code=request.POST.get('code')
        if request.session.get('code')==code:
            user_obj=auth.authenticate(request,username=username,password=password)
            if user_obj:
                auth.login(request,user_obj)
                back_dic['url']='/home/'
            else:
                back_dic['code']=2000
                back_dic['msg']='用户名或密码错误'
        else:
            back_dic['code']=3000
            back_dic['msg']='验证码错误'
            print(back_dic)
        return JsonResponse(back_dic)
    return render(request,'login.html')
def get_random():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)
def get_code(request):
    img_obj=Image.new('RGB',(350,35),get_random())
    img_draw=ImageDraw.Draw(img_obj)
    img_font=ImageFont.truetype('static/ttf/Freeform710BT-Regular.ttf',30)
    code=''
    for i in range(5):
        random_upper=chr(random.randint(65,90))
        random_lower=chr(random.randint(97,122))
        random_int=str(random.randint(0,9))
        tmp=random.choice([random_int,random_lower,random_upper])
        img_draw.text((i*60+60,-2),tmp,get_random(),img_font)
        code+=tmp
    print(code)
    request.session['code']=code
    io_obj=BytesIO()
    img_obj.save(io_obj,'png')
    return HttpResponse(io_obj.getvalue())
def home(request):
    article_queryset=models.Article.objects.all()
    return render(request,'home.html',locals())
@login_required
def set_password(request):
   back_dic={'code':1000,'msg':''}
   if request.method=='POST':
      old_password=request.POST.get('old_password')
      new_password=request.POST.get('new_password')
      re_password=request.POST.get('confirm_password')
      form_obj=request.user.check_password(old_password)
      if form_obj:
          if new_password==re_password:
              request.user.set_password(new_password)
              request.user.save()
              back_dic['msg']='修改成功'
          else:
              back_dic['code']=1001
              back_dic['msg']='两次密码不一致'
      else:
          back_dic['code']=1002
          back_dic['msg']='原密码错误'
   print(back_dic)
   return JsonResponse(back_dic)

@login_required
def logout(request):
    auth.logout(request)
    return redirect('/home/')
@login_required
def set_img(request):
    blog = request.user.blog
    username = request.user.username
    return render(request,'set_img.html',locals())
def site(request,username,**kwargs):
    user_obj=models.UserInfo.objects.filter(username=username).first()
    if not user_obj:
        return render(request,'error.html')
    blog=user_obj.blog
    article_list=models.Article.objects.filter(blog=blog)
    if kwargs:
        condition=kwargs.get('condition')
        param=kwargs.get('param')
        if condition=='category':
            article_list=article_list.filter(categroy_id=param)
        elif condition=='tag':
            article_list=article_list.filter(tags__id=param)
        else:
            year,month=param.split('-')
            article_list=article_list.filter(create_time__year=year,create_time__month=month)
    categroy_list=models.Category.objects.filter(blog=blog).annotate(count_num=Count('article__pk')).values_list('name','count_num','pk')
    tag_list=models.Tag.objects.filter(blog=blog).annotate(count_num=Count('article__pk')).values_list('name','count_num','pk')
    date_list = models.Article.objects.filter(blog=blog).annotate(month=TruncMonth('create_time')).values(
        'month').annotate(count_num=Count('pk')).values_list('month', 'count_num')
    return render(request,'site.html',locals())
def article(request,username,article_id):
    article_obj=models.Article.objects.filter(pk=article_id).first()
    user_obj = models.UserInfo.objects.filter(username=username).first()
    blog = user_obj.blog
    article_list = models.Article.objects.filter(blog=blog)
    categroy_list = models.Category.objects.filter(blog=blog).annotate(count_num=Count('article__pk')).values_list(
        'name', 'count_num', 'pk')
    tag_list = models.Tag.objects.filter(blog=blog).annotate(count_num=Count('article__pk')).values_list('name',
                                                                                                         'count_num',
                                                                                                         'pk')
    date_list = models.Article.objects.filter(blog=blog).annotate(month=TruncMonth('create_time')).values(
        'month').annotate(count_num=Count('pk')).values_list('month', 'count_num')
    if not article_obj:
        return render(request,'error.html')
    return render(request,'article.html',locals())
from django.db.models import F
def up_or_down(request):
    if request.is_ajax():
        back_dic = {'code': 1000, 'msg': ''}
        if request.user.is_authenticated:
            article_id = request.POST.get('article_id')
            is_up = request.POST.get('is_up')
            is_up = json.loads(is_up)  # 记得转换
            article_obj = models.Article.objects.filter(pk=article_id).first()
            if not article_obj.blog.userinfo == request.user:
                is_click = models.UpAndDown.objects.filter(user=request.user, article=article_obj)
                if not is_click:
                    if is_up:
                        models.Article.objects.filter(pk=article_id).update(up_num=F('up_num') + 1)
                        back_dic['msg'] = '点赞成功'
                    else:
                        models.Article.objects.filter(pk=article_id).update(down_num=F('down_num') + 1)
                        back_dic['msg'] = '点踩成功'
                    models.UpAndDown.objects.create(user=request.user, article=article_obj, is_up=is_up)
                else:
                    back_dic['code'] = 1001
                    back_dic['msg'] = '你已经点过了,不能再点了'  # 这里你可以做的更加的详细 提示用户到底点了赞还是点了踩
            else:
                back_dic['code'] = 1002
                back_dic['msg'] = '你个臭不要脸的!'
        else:
            back_dic['code'] = 1003
            back_dic['msg'] = '请先<a href="/login/">登陆</a>'
        return JsonResponse(back_dic)